package com.kpa.demo.ui.main.view

import android.os.Bundle
import android.util.Log
import androidx.appcompat.app.AppCompatActivity
import androidx.lifecycle.Observer
import androidx.lifecycle.ViewModelProviders
import androidx.recyclerview.widget.DividerItemDecoration
import androidx.recyclerview.widget.LinearLayoutManager
import com.kpa.demo.R
import com.kpa.demo.data.api.ApiHelper
import com.kpa.demo.data.http.NetWorkHelper
import com.kpa.demo.data.model.Coming
import com.kpa.demo.ui.base.RequestState
import com.kpa.demo.ui.base.ViewModelFactory
import com.kpa.demo.ui.main.adapter.ComingAdapter
import com.kpa.demo.ui.main.adapter.MainAdapter
import com.kpa.demo.ui.main.viewmodel.GirlViewModel
import kotlinx.android.synthetic.main.activity_main.*

class MainActivity : AppCompatActivity() {
    private lateinit var girlViewModel: GirlViewModel
    private lateinit var adapter: MainAdapter
    private lateinit var comings: List<Coming>
    private lateinit var comingAdapter: ComingAdapter
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        setupViewModel()
        setupObserver()
        setupUI()
    }

    private fun setupObserver() {
        comings = mutableListOf()
        girlViewModel.stateLiveData.observe(this, Observer {
            when (it) {
                RequestState.LoadState -> Log.d("MainActivity", "setupObserver: 请求中....")
                RequestState.SuccessState -> Log.d("MainActivity", "setupObserver: 请求成功!")
                is RequestState.ErrorState -> {
                    Log.d("MainActivity", "setupObserver: 请求失败,原因:" + it.message)
                }
            }
        })

        girlViewModel.getDataBean().observe(this, {
            val coming = it.data.coming
            comings = coming
            comingAdapter.notifyDataSetChanged()
            Log.d("TAG", "setupObserver: $coming")
        })
    }

    private fun setupViewModel() {
        girlViewModel =
            ViewModelProviders.of(this, ViewModelFactory(ApiHelper(NetWorkHelper.apiService)))
                .get(GirlViewModel::class.java)
    }

    private fun setupUI() {
        recyclerView.layoutManager = LinearLayoutManager(this)
        comingAdapter = ComingAdapter(this, comings)
        adapter = MainAdapter(arrayListOf())
        recyclerView.addItemDecoration(
            DividerItemDecoration(
                recyclerView.context,
                (recyclerView.layoutManager as LinearLayoutManager).orientation
            )
        )
        recyclerView.adapter = comingAdapter

    }
}